<template>
  <div class="page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="page-title">
        <h2>🎓 专业管理</h2>
        <p class="page-subtitle">管理专业信息，包括专业代码、学制、所属学院等</p>
      </div>
      <div class="page-actions">
        <el-button type="primary" @click="showAddModal = true; dialogVisible = true">
          <el-icon><Plus /></el-icon>
          新增专业
        </el-button>
        <el-button @click="refreshProfessions">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 内容卡片 -->
    <el-card class="content-card">
      <!-- 搜索 -->
      <template #header>
        <div class="search-section">
          <div class="search-box">
            <el-input
              v-model="searchQuery"
              placeholder="搜索专业名称..."
              clearable
              style="width: 300px"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>
      </template>

      <!-- 专业列表 -->
      <el-table :data="paginatedProfessions" stripe>
        <el-table-column label="专业名称" min-width="220">
          <template #default="{ row }">
            <div class="profession-info">
              <div class="profession-name">{{ row.name }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="180">
          <template #default="{ row }">
            <span>{{ formatTime(row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" min-width="180">
          <template #default="{ row }">
            <span>{{ formatTime(row.updateTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button size="small" type="warning" @click="editProfession(row)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button size="small" type="danger" @click="deleteProfession(row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalProfessions"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑专业对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="showAddModal ? '新增专业' : '编辑专业'"
      width="600px"
      :before-close="closeModal"
    >
      <el-form
        ref="formRef"
        :model="professionForm"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="专业名称" prop="name">
          <el-input
            v-model="professionForm.name"
            placeholder="请输入专业名称"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="professionForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeModal">取消</el-button>
          <el-button type="primary" @click="saveProfession">
            {{ showAddModal ? '新增' : '保存' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Search, Edit, Delete } from '@element-plus/icons-vue'
import { queryProfessionAPI, addProfessionAPI, updateProfessionAPI, deleteProfessionAPI } from '@/apis/professionAPI'

// 响应式数据
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const showAddModal = ref(false)
const showEditModal = ref(false)
const editingProfession = ref(null)
const dialogVisible = ref(false)
const formRef = ref(null)

// 专业表单（与后端字段对齐）
const professionForm = ref({
  id: '',
  name: '',
  status: 1
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入专业名称', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 数据源
const professions = ref([])

// 计算属性
const filteredProfessions = computed(() => {
  let filtered = professions.value

  // 搜索过滤（按名称）
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(profession => 
      (profession.name || '').toLowerCase().includes(query)
    )
  }

  return filtered
})

const totalProfessions = computed(() => filteredProfessions.value.length)

// 分页数据
const paginatedProfessions = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredProfessions.value.slice(start, end)
})

// 辅助展示格式化
const formatTime = (t) => {
  if (!t) return ''
  try {
    const d = new Date(t)
    const y = d.getFullYear()
    const m = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    const hh = String(d.getHours()).padStart(2, '0')
    const mm = String(d.getMinutes()).padStart(2, '0')
    const ss = String(d.getSeconds()).padStart(2, '0')
    return `${y}-${m}-${day} ${hh}:${mm}:${ss}`
  } catch {
    return String(t)
  }
}

// 方法
const getStatusText = (status) => (Number(status) === 1 ? '启用' : '禁用')
const getStatusTagType = (status) => (Number(status) === 1 ? 'success' : 'info')

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

const fetchProfessions = async () => {
  try {
    const res = await queryProfessionAPI()
    const list =res.data
    professions.value = list
  } catch (e) {
    ElMessage.error('获取专业列表失败')
  }
}

const refreshProfessions = async () => {
  await fetchProfessions()
  ElMessage.success('数据已刷新')
}

const editProfession = (profession) => {
  editingProfession.value = profession
  professionForm.value = { id: profession.id, name: profession.name, status: profession.status }
  showEditModal.value = true
  dialogVisible.value = true
}

const deleteProfession = async (profession) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除专业 "${profession.name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    await deleteProfessionAPI(profession.id)
    ElMessage.success('删除成功')
    fetchProfessions()
  } catch {
    ElMessage.info('已取消删除')
  }
}

const saveProfession = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (showAddModal.value) {
      await addProfessionAPI({ name: professionForm.value.name, status: professionForm.value.status })
      ElMessage.success('新增专业成功')
    } else {
      await updateProfessionAPI({ id: professionForm.value.id, name: professionForm.value.name, status: professionForm.value.status })
      ElMessage.success('编辑专业成功')
    }
    await fetchProfessions()
    closeModal()
  } catch (error) {
    ElMessage.error('操作失败，请重试')
  }
}

const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  dialogVisible.value = false
  editingProfession.value = null
  professionForm.value = {
    id: '',
    name: '',
    status: 1
  }
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

onMounted(() => {
  fetchProfessions()
})
</script>

<style scoped>
.page-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 2rem;
  padding-bottom: 1.5rem;
  border-bottom: 1px solid var(--border-light);
}

.page-title h2 {
  font-size: 1.875rem;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: 0.5rem;
}

.page-subtitle {
  color: var(--text-secondary);
  font-size: 0.875rem;
  margin: 0;
}

.page-actions {
  display: flex;
  gap: 0.75rem;
  align-items: center;
}

.content-card {
  margin-bottom: 2rem;
}

.search-section {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.search-box {
  flex: 1;
  max-width: 300px;
}

.filter-section {
  display: flex;
  gap: 0.5rem;
}

.profession-info {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.profession-name {
  font-weight: 500;
  color: var(--text-primary);
  font-size: 0.875rem;
}

.profession-desc {
  font-size: 0.75rem;
  color: var(--text-muted);
  line-height: 1.4;
}

.student-count {
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

.count {
  font-weight: 600;
  color: var(--text-primary);
  font-size: 0.875rem;
}

.label {
  color: var(--text-muted);
  font-size: 0.75rem;
}

.action-buttons {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 1rem;
}

.dialog-footer {
  text-align: right;
}
</style>
